package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.util.DateTimeZoneConverter;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import lombok.Builder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备Service业务层处理
 *
 * @author ruoyi
 * @date 2025-08-02
 */
@Builder
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient iotdAClient;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 查询设备
     *
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id) {
        return getById(id);
    }

    /**
     * 查询设备列表
     *
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     *
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备
     *
     * @param device 设备
     * @return 结果
     */
    @Override
    public int updateDevice(Device device) {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备
     *
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备信息
     *
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 从物联网平台同步产品列表
     *
     * @return
     */
    @Override
    public String syncProductList() {
        ListProductsRequest request = new ListProductsRequest();
        request.setLimit(50);
        ListProductsResponse response = iotdAClient.listProducts(request);
        List<ProductSummary> products = response.getProducts();
        redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST, JSONUtil.toJsonStr(products));
        return "同步成功！";
    }

    /**
     * 查询所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        String jsonstr = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST);
        if (StringUtils.isEmpty(jsonstr)) {
            return Collections.emptyList();
        }

        return JSONUtil.toList(jsonstr, ProductVo.class);
    }

    /**
     * 注册设备
     *
     * @param dto
     */
    @Override
    public void register(DeviceDto dto) {
        //1.查询设备名称是否重复
        LambdaQueryWrapper<Device> query = new LambdaQueryWrapper<>();
        query.eq(Device::getDeviceName, dto.getDeviceName());
        long count = count(query);
        if (count > 0) {
            throw new RuntimeException("设备名称已存在！");
        }
        //2.查询设备标识是否重复
        LambdaQueryWrapper<Device> query1 = new LambdaQueryWrapper<>();
        query1.eq(Device::getNodeId, dto.getNodeId());
        count = count(query1);
        if (count > 0) {
            throw new RuntimeException("设备标识已存在！");
        }
        //如果
        if (dto.getLocationType() == 0){
            dto.setPhysicalLocationType(-1);
        }

        //3.确定同一位置是否绑定了相同的产品
        LambdaQueryWrapper<Device> query2 = new LambdaQueryWrapper<>();
        query2.eq(Device::getProductKey, dto.getProductKey())
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(Device::getPhysicalLocationType, dto.getPhysicalLocationType());
        count = count(query2);
        if (count > 0) {
            throw new RuntimeException("同一位置已绑定相同产品！");
        }
        //4.注册设备->在华为的IOT中创建设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.withProductId(dto.getProductKey());
        body.withDeviceName(dto.getDeviceName());
        body.withNodeId(dto.getNodeId());
        //秘钥设置
        AuthInfo authInfo = new AuthInfo();
        authInfo.withSecret(UUID.randomUUID().toString().replace("-", ""));
        body.setAuthInfo(authInfo);
        request.setBody(body);
        AddDeviceResponse response;
        try {
            response = iotdAClient.addDevice(request);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("物联网接口 - 注册设备，调用失败");
        }
        //5.保存设备信息->保存到本地数据库中
        Device device = BeanUtil.toBean(dto, Device.class);
        device.setSecret(authInfo.getSecret());
        device.setIotId(response.getDeviceId());
        save(device);
    }

    /**
     * 查询设备详情
     *
     * @param iotId 设备的IoT标识
     * @return
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //查询本地设备数据
        Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if (ObjectUtil.isEmpty(device)) {
            return null;
        }
        //调用华为云接口查询设备详情
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response;
        try {
            response = iotdAClient.showDevice(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询设备详情，调用失败");
        }
        //属性拷贝
        DeviceDetailVo deviceVo = BeanUtil.toBean(device, DeviceDetailVo.class);
        deviceVo.setDeviceStatus(response.getStatus());
        String activeTimeStr = response.getActiveTime();
        //日期转换
        if (StringUtils.isNotEmpty(activeTimeStr)) {
            //把字符串转换为LocalDateTime
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            //日期时区转换
            deviceVo.setActiveTime(DateTimeZoneConverter.utcToShanghai(activeTime));
        }
        return deviceVo;
    }

    /**
     * 查询设备服务属性
     *
     * @param iotId 设备的IoT标识
     * @return
     */
    @Override
    public AjaxResult queryServiceProperties(String iotId) {

        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = iotdAClient.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口 - 查询设备影子，调用失败");
        }
        List<DeviceShadowData> shadow = response.getShadow();
        if (CollUtil.isEmpty(shadow)) {
            List<Object> emptyList = Collections.emptyList();
            return AjaxResult.success(emptyList);
        }
        //获取上报数据的reported （参考返回的json数据）
        DeviceShadowProperties reported = shadow.get(0).getReported();
        //把数据转换为JSONObject(map)，方便处理
        JSONObject jsonObject = JSONUtil.parseObj(reported.getProperties());
        //遍历数据，封装到list中
        List<Map<String, Object>> list = new ArrayList<>();
        //事件上报时间
        String eventTimeStr = reported.getEventTime();
        //把字符串转换为LocalDateTime
        LocalDateTime eventTimeLocalDateTime = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
        //时区转换
        LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(eventTimeLocalDateTime);

        // k:属性标识，v:属性值
        jsonObject.forEach((k, v) -> {
            Map<String, Object> map = new HashMap<>();
            map.put("functionId", k);
            map.put("value", v);
            map.put("eventTime", eventTime);
            list.add(map);
        });

        //数据返回
        return AjaxResult.success(list);

    }

    /**
     * 修改设备
     *
     * @param device 设备
     * @return 影响行数
     */
    @Override
    public int update(DeviceDto device) {
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.setDeviceId(device.getIotId());
        UpdateDevice body = new UpdateDevice();
        body.withDeviceName(device.getDeviceName());
        request.setBody(body);
        try {
            iotdAClient.updateDevice(request);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("物联网接口 - 修改设备，调用失败");
        }
        //修改本地数据库
        Device updateDevice = BeanUtil.toBean(device, Device.class);
        try {
            return updateById(updateDevice) ? 1 : 0;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 删除设备
     *
     * @param iotId 设备的IoT标识
     * @return 影响行数
     */
    @Override
    public int remove(String iotId) {
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setDeviceId(iotId);
        try {
            iotdAClient.deleteDevice(request);
        }catch (Exception e){
            e.printStackTrace();
            throw new BaseException("物联网接口 - 删除设备，调用失败");
        }
        return remove(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId)) ? 1 : 0;
    }
}
